package com.itlong.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceAuthFileDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListAuthFileConsumeRecordsDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListAuthRulesDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListDTO;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.PO.RoomInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.DeviceAuthFileVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceWhiteListAuthRulesVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceWhiteListVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnParamEncrypt;
import com.itlong.cloud.enumerate.CloudDeviceErrorCodeEnum;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.equip.commons.ICloudElevatorServiceClient;
import com.itlong.cloud.equip.commons.ICloudTalkPushCloudIntercomChangeLogServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListAuthFileConsumeRecordsServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListAuthFileServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListAuthRulesServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListServiceClient;
import com.itlong.cloud.equip.property.ICloudIntercomServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.node.MapUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

/**
 * <desc>
 * 云门禁设备接口控制器
 * </desc>
 *
 * @createDate 2019-02-21.
 */
@RestController
@RequestMapping("/smartCommunity/interface")
@RefreshScope
public class CloudEntranceController {
    private static final Logger LOG = LoggerFactory.getLogger(CloudEntranceController.class);

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;

    @Autowired
    ICloudElevatorServiceClient iCloudElevatorServiceClient;

    @Autowired
    ICloudIntercomServiceClient iCloudIntercomServiceClient;

    @Autowired
    IOperateDeviceWhiteListAuthFileConsumeRecordsServiceClient authFileConsumeRecordsServiceClient;

    @Autowired
    IOperateDeviceWhiteListServiceClient deviceWhiteListServiceClient;

    @Autowired
    IOperateDeviceWhiteListAuthRulesServiceClient iOperateDeviceWhiteListAuthRulesServiceClient;

    @Autowired
    IOperateDeviceWhiteListAuthFileServiceClient iOperateDeviceWhiteListAuthFileServiceClient;

    @Autowired
    ICloudTalkPushCloudIntercomChangeLogServiceClient changeLogServiceClient;


    @Autowired
    IPropertyEquipServiceClient equipServiceClient;


    /**
     * <desc>
     * 云门禁上报设备的能力集信息
     * </desc>
     *
     * @param token
     * @param capacitySet 表示设备支持哪些功能，有哪些能力 json String数据
     * @return
     * @author Juguang.S
     * @createDate 2019-02-21
     */
    @RequestMapping(path = "/device/entrance/reportCapacitySet")
    @ResponseBody
    public Object reportCapacitySet(String token, String capacitySet, String sn,String  deviceType, String doorCount, HttpServletRequest request) {
        try {
            Map<String, Object> params = null;
            if (StringUtils.isBlank(token)) {
                params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                token = params.get("token").toString();
                capacitySet = JsonUtil.toJSON(params.get("capacitySet"));
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                deviceType  = StringHandlerUtil.getNullOrStringForObject(params.get("deviceType"));
                doorCount = StringHandlerUtil.getNullOrStringForObject(params.get("doorCount"));
            }
            if (StringUtils.isBlank(capacitySet) || StringUtils.isBlank(sn) || StringUtils.isBlank(doorCount)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iPropertyEquipServiceClient.reportCapacitySet(sn, capacitySet, Integer.parseInt(doorCount),deviceType);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云门禁】上报设备的能力集信息失败", e);
        }
    }

    /**
     * <desc>
     * 获取设备固定密码
     * </desc>
     *
     * @param dto 云门禁分页dto类
     * @return
     * @author Juguang.S
     * @createDate 2019/02/22
     */
    @RequestMapping(path = "/device/entrance/pullDevicePwd")
    @ResponseBody
    public Object pullDevicePwd(CloudEntrancePageDTO dto, HttpServletRequest request) {
        try {
            if (dto.getToken() == null) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params != null) {
                    dto = (CloudEntrancePageDTO) MapUtil.mapToObject(params, CloudEntrancePageDTO.class);
                }
            }
            if (StringUtils.isBlank(dto.getSn())) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isEmpty(dto.getDoorCount().toString()) || StringUtils.isEmpty(dto.getDoorNum().toString())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (dto.getPage() == null || dto.getPageSize() == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PAGE_ERROR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iPropertyEquipServiceClient.pullDevicePwd(dto));
        } catch (Exception e) {
            throw new DataAccessException("【云门禁】获取设备固定密码失败", e);
        }
    }

    /**
     * <desc>
     * 获取云门禁设备所有者的认证信息
     * <desc/>
     *
     * @return 标准格式化相应信息
     * @author wangzhi
     * @createDate 2019/04/30
     */
    @RequestMapping(value = "/device/entrance/pullDeviceAuthInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullDeviceAuthInfo(CloudIntercomDeviceAuthGetDTO getDTO, HttpServletRequest request) {
        String elapsedtime = "【pullDeviceAuthInfo云门禁设备所有者的认证信息】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            if (getDTO.getToken() == null) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params != null) {
                    getDTO = JsonUtil.decode(JsonUtil.toJSON(params), new TypeReference<CloudIntercomDeviceAuthGetDTO>() {
                    });
                }
            }
            //合法性判断
            if (null == getDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(getDTO.getSn())) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            elapsedtime += ";getDeviceServeRoomsByPage开始执行：" + DateUtil.fomatDate1(new Date());
            //获取服务的房间列表及其住户信息
            Page<CloudEntranceDeviceAuthVO.Room> roomPage = iPropertyEquipServiceClient.getDeviceServeRoomsByPage(getDTO);
            elapsedtime += ";getUsersByRoomIds开始执行：" + DateUtil.fomatDate1(new Date());
            if (null != roomPage && roomPage.getRows() != null && roomPage.getRows().size() > 0) {
                List<String> roomIds = new ArrayList<>();
                for (int i = 0; i < roomPage.getRows().size(); i++) {
                    roomIds.add(roomPage.getRows().get(i).getRoomId());
                    //每50个房间获取一次
                    if (roomIds.size() == 50) {
                        List<CloudElevatorDeviceAuthVO.RoomUser> users = iCloudElevatorServiceClient.getUsersByRoomIds(StringUtils.join(roomIds, ','));
                        if (users != null && !users.isEmpty()) {
                            users.forEach(usr -> {
                                CloudEntranceDeviceAuthVO.RoomUser roomUser = new CloudEntranceDeviceAuthVO.RoomUser();
                                BeanUtils.copyProperties(usr, roomUser);
                                for (int j = 0; j < roomPage.getRows().size(); j++) {
                                    CloudEntranceDeviceAuthVO.Room room = roomPage.getRows().get(j);
                                    if (room.getRoomId().equals(roomUser.getRoomId())) {
                                        if (room.getRoomUserArr() == null) {
                                            room.setRoomUserArr(new ArrayList<>());
                                            room.getRoomUserArr().add(roomUser);
                                        } else {
                                            room.getRoomUserArr().add(roomUser);
                                        }
                                    }
                                }
                            });
                        }
                        roomIds.clear();
                    }
                }
                if (!roomIds.isEmpty()) {
                    //1.通过门禁设备查询到设备的所在单元和楼栋信信息
                    List<Map<String, String>> addressMap = iCloudIntercomServiceClient.getUnitIdByEntranceDeviceUnique(StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()));
                    //去除重复的电梯设备机号
                    Set<CloudElevatorVO> DeviceUniques = new HashSet<>();
                    for (Map<String, String> map : addressMap) {
                    //2.通过地址查询到该地址下的电梯信息集合（包含电梯的正背门信息），用于跟用户的设置的常用楼层的设备进行比较
                    List<CloudElevatorVO> deviceUniqueList= iCloudIntercomServiceClient.getElevatorLiftDoorTypeListByAddress(map);
                      //  LOG.info("====通过地址查询到该地址下的电梯信息集合=====>{}",deviceUniqueList.toString());
                        for (CloudElevatorVO CloudElevator : deviceUniqueList) {
                            DeviceUniques.add(CloudElevator);
                        }
                    }
                    List<CloudElevatorDeviceAuthVO.RoomUser> users = iCloudElevatorServiceClient.getUsersByRoomIds(StringUtils.join(roomIds, ','));
                    if (users != null && !users.isEmpty()) {
                        users.forEach((CloudElevatorDeviceAuthVO.RoomUser usr) -> {
                            CloudEntranceDeviceAuthVO.RoomUser roomUser = new CloudEntranceDeviceAuthVO.RoomUser();
                            BeanUtils.copyProperties(usr, roomUser);
                            for (int j = 0; j < roomPage.getRows().size(); j++) {
                                // 组装vip标识
                                if (usr.getUserLabel() == null) {
                                    usr.setIsVip(0);
                                } else {
                                    usr.setIsVip(Arrays.asList(usr.getUserLabel().split(",")).contains("1") ? 1 : 0);
                                }
                                //组装常用楼层和公共楼层
                                //1.得到用户所拥有的楼层机号对应关系
                                String commonFloor = StringHandlerUtil.getNullOrStringForObject(usr.getCommonFloor());
                                String publicFloor = StringHandlerUtil.getNullOrStringForObject(usr.getPublicFloor());
                                //2.获取当前云门禁的地址
//                              //3.获取当前地址的下的电梯 正背们和机号
                                //RoomInfoPO roomInfo= iCloudIntercomServiceClient.getUnitIdByRoomInfoId(roomPage.getRows().get(j).getRoomId());
                             //   RoomInfoPO roomInfo= iCloudIntercomServiceClient.getUnitIdByRoomInfoId(usr.getRoomId());
                             //   List<CloudElevatorVO>    DeviceUniques = equipServiceClient.getElevatorListByAddress(roomInfo.getUnitId());
                                    //4.比对用户所用的常用楼层的对应的机号的楼层号
                                    net.sf.json.JSONObject jsonCommonFloor = null;
                                    net.sf.json.JSONObject jsonPublicFloor = null;
                                    if (commonFloor != null) {
                                        jsonCommonFloor = net.sf.json.JSONObject.fromObject(commonFloor);
                                    }
                                    if (publicFloor != null) {
                                        jsonPublicFloor = net.sf.json.JSONObject.fromObject(publicFloor);
                                    }

                                    for (CloudElevatorVO cloudElevatorVO : DeviceUniques) {
                                      /*   Map<String, Object> elevator = null;
                                       try {
                                            elevator = changeLogServiceClient.getElevatorByDeviceUnique(cloudElevatorVO.getDeviceUnique());
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }*/
                                        if (commonFloor == null) {
                                           // if ("1".equals((elevator==null?null:elevator.get("liftDoorType")+""))) {
                                            if ("1".equals(cloudElevatorVO==null?"":cloudElevatorVO.getLiftDoorType())) {
                                                //正门常用楼层
                                                usr.setFrontCommonFloor("");
                                                roomUser.setFrontCommonFloor("");
                                            } else {
                                                usr.setBackCommonFloor("");
                                                roomUser.setBackCommonFloor("");
                                            }
                                        } else {
                                            if (jsonCommonFloor.containsKey(cloudElevatorVO.getDeviceUnique())) {
                                             //   if ("1".equals((elevator==null?"":elevator.get("liftDoorType")+""))) {
                                                if ("1".equals(cloudElevatorVO.getLiftDoorType()==null?"":cloudElevatorVO.getLiftDoorType())) {
                                                    //正门常用楼层
                                                    usr.setFrontCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                    roomUser.setFrontCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());

                                                } else {
                                                    usr.setBackCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                     roomUser.setBackCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());

                                                }
                                            }
                                        }
                                        if (publicFloor == null) {
                                         //   if ("1".equals((elevator==null?"":elevator.get("liftDoorType")+""))) {
                                            if ("1".equals(cloudElevatorVO==null?"":cloudElevatorVO.getLiftDoorType())) {
                                                //正门常用楼层
                                                usr.setFrontPublicFloor("");
                                                roomUser.setFrontPublicFloor("");
                                            } else {
                                                usr.setBackPublicFloor("");
                                                roomUser.setBackPublicFloor("");
                                            }
                                        } else {
                                            if (jsonPublicFloor.containsKey(cloudElevatorVO.getDeviceUnique())) {
                                           //     if ("1".equals((elevator==null?null:elevator.get("liftDoorType")+""))) {
                                                if ("1".equals(cloudElevatorVO.getLiftDoorType()==null?"":cloudElevatorVO.getLiftDoorType())) {
                                                    //正门常用楼层
                                                    usr.setFrontPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                    roomUser.setFrontPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());

                                                    roomUser.setFrontPublicFloor(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                } else {
                                                    usr.setBackPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                    roomUser.setBackPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                                }
                                            }
                                        }

                                    }
                                CloudEntranceDeviceAuthVO.Room room = roomPage.getRows().get(j);
                                if (room.getRoomId().equals(roomUser.getRoomId())) {
                                    if (room.getRoomUserArr() == null) {
                                        room.setRoomUserArr(new ArrayList<>());
                                        room.getRoomUserArr().add(roomUser);
                                    } else {
                                        room.getRoomUserArr().add(roomUser);
                                    }
                                }
                            }
                        });
                    }
                }
            }

            CloudEntranceDeviceAuthVO deviceAuthVO = new CloudEntranceDeviceAuthVO();
            deviceAuthVO.setDeviceAuthArr(roomPage.getRows());
            deviceAuthVO.setCurrentTotal(roomPage.getRows().size());
            deviceAuthVO.setTotal(roomPage.getPage().getTotalNumber());
            deviceAuthVO.setPage(roomPage.getPage().getCurrentPage());
            deviceAuthVO.setHaveNext(roomPage.getPage().getTotalPage() - roomPage.getPage().getCurrentPage() > 0 ? 1 : 0);
            //最后一页并且需要访客信息的时候
            if (deviceAuthVO.getHaveNext() == 0) {
                //拼接访客信息
                List<CloudEntranceDeviceAuthVO.Room> deviceAuthArr = roomPage.getRows();
                //查询该设备访客下的信息
                List<CloudIntercomVisitorVO> list = iPropertyEquipServiceClient.getVisitorInfoByDevice(getDTO);
                for (CloudIntercomVisitorVO vo : list) {
                    CloudEntranceDeviceAuthVO.Room room = new CloudEntranceDeviceAuthVO.Room();
                    CloudEntranceDeviceAuthVO.RoomUser roomUser = new CloudEntranceDeviceAuthVO.RoomUser();
                    List<CloudEntranceDeviceAuthVO.RoomUser> listRoomUser = new ArrayList<>();
                    roomUser.setUserId(vo.getVFaceId() == null ? "" : vo.getVFaceId());
                    roomUser.setStartTime(vo.getStartTime());
                    roomUser.setEndTime(vo.getEndTime());
                    roomUser.setRoomId(vo.getRoomId());
                    roomUser.setVisitorType(1);
                    roomUser.setUserName(vo.getVisitorName() == null ? "" : vo.getVisitorName());
                    roomUser.setIdcardKey(vo.getIdcardKey() == null ? "" : vo.getIdcardKey());
                    roomUser.setFacePicUrl(vo.getFacePicUrl() == null ? "" : vo.getFacePicUrl());
                    room.setRoomId(vo.getRoomId());
                    room.setRoomNum(vo.getRoomNum());
                    room.setLiftDoorType(vo.getLiftDoorType());
                    room.setSoftCardNums(vo.getSoftCardNums() == null ? "" : vo.getSoftCardNums());
                    room.setArrearsTime(vo.getArrearsTime());
                    room.setOpenPwd(vo.getOpenPwd() == null ? "" : vo.getOpenPwd());
                    room.setStatus(vo.getRoomStatus().toString());
                    room.setDoorNum(vo.getDoorNum());

                    listRoomUser.add(roomUser);
                    room.setRoomUserArr(listRoomUser);
                    deviceAuthArr.add(room);
                }
            }
          /*  LOG.info(String.format("【pullDeviceAuthInfo返回数据】 sn:%s，deviceAuth：%s",
                   getDTO.getSn(), JSON.toJSONString(deviceAuthVO)));*/
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), deviceAuthVO);
        } catch (Exception e) {
            throw new DataAccessException("【云门禁】获取云门禁设备所有者的认证信息失败", e);
        } finally {
            elapsedtime += ";【pullDeviceAuthInfo获取云门禁设备所有者的认证信息】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }

    /**
     * <desc>
     * 云门禁（一体式人脸识别门禁）设备获取白名单授权文件
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-08-12 15:21
     * @Param password 获取白名单授权文件密码   mac 获取对应授权文件的设备的MAC地址
     * @Return
     * @Exception
     */

    @PostMapping("/device/entrance/getWhiteListAuthFile")
    @ResponseBody
    @UnParamEncrypt
    public Object getWhiteListAuthFile(String password, String mac, HttpServletRequest request) {
        try {
            Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
            password = params.get("password").toString();
            mac = params.get("mac").toString();
            Date nowTime = new Date();
            if (StringUtils.isBlank(password)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PASSWORD_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(mac)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_NULL.getErrorCode());
            }
            //1判断设备mac地址是否在白名单中
            OperateDeviceWhiteListVO whiteListByMac = deviceWhiteListServiceClient.getWhiteListByMac(mac);
            if (whiteListByMac == null) {
                //1.如果白名单里面确实没有这个mac设备，新增白名单记录为设备异常标记为2 ，做新增白名单记录 ，exception_flag为2：异常
                OperateDeviceWhiteListDTO whiteListDTO = new OperateDeviceWhiteListDTO();
                whiteListDTO.setExceptionFlag(2);
                whiteListDTO.setChangeFlag(2);
                whiteListDTO.setMacAddress(mac);
                //初始请求次数为1次
                whiteListDTO.setRequestTimes(1);
                whiteListDTO.setLastUploadTime(nowTime);
                deviceWhiteListServiceClient.save(whiteListDTO);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DEVICE_MAC_IS_NULL.getErrorCode());
            }
            if (whiteListByMac != null && "2".equals(whiteListByMac.getChangeFlag())) {
                //2.如果白名单里面有这个Mac的记录，但是change_flag为2：未转换
                OperateDeviceWhiteListDTO whiteListDTO = new OperateDeviceWhiteListDTO();
                whiteListDTO.setWhiteListId(whiteListByMac.getWhiteListId());
                whiteListDTO.setRequestTimes(whiteListByMac.getRequestTimes() + 1);
                whiteListDTO.setLastUploadTime(nowTime);
                deviceWhiteListServiceClient.update(whiteListDTO);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DEVICE_MAC_IS_NULL.getErrorCode());
            }
            if (whiteListByMac != null) {
                if ("1".equals(whiteListByMac.getActivateStatus()) && DataStatusEnum.BAN.getType().equals(whiteListByMac.getStatus())) {
                    ErrorCode errorCode = CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_ERROR.getErrorCode();
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_ERROR.getErrorCode(), String.format(errorCode.getCodeMsg(), mac));
                }
            }
            //获取授权规则信息
            OperateDeviceWhiteListAuthRulesDTO rulesDTO = new OperateDeviceWhiteListAuthRulesDTO();
            rulesDTO.setPassword(Base64.encode(DesEncryptUtil.Encrypt(URLEncoder.encode(new String(password.getBytes()), "utf-8").getBytes(), PlatformConstants.OPERATE_USER_PASSWORD_KEY)));
            //通过输入的授权密码查询授权规则信息  得到 授权文件次数 授权文件的有效时间 授权文件逻辑id
            //2.校验授权文件密码是否输入正确
            List<OperateDeviceWhiteListAuthRulesVO> rules =
                    iOperateDeviceWhiteListAuthRulesServiceClient.getWhiteListAuthRulesByList(rulesDTO);
            if (rules.size() == 0) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PASSWORD_IS_ERROR.getErrorCode());
            }

            String ruleId = null;
            //3.校验获取的设备授权文件的时间

            List<Object> flagList = new ArrayList<>();
            for (OperateDeviceWhiteListAuthRulesVO rule : rules) {
                Date newdate = new Date();//获取激活文件时间
                String beginDateTime = rule.getStartTime();//预先设置好的授权文件有效的开始时间
                String endDateTime = rule.getEndTime();//预先设置好的授权文件有效的结束时间
                boolean flag = DateUtil.getTimeQuantum("yyyy-MM-dd HH:mm:ss", newdate, beginDateTime, endDateTime);
                // 当校验的是获取文件时间在有效期内并且可用次数和已使用次数不相等，得到它的规则id，拿出来传给前端，方便后面更新规则表的信息
                if (flag && !rule.getAmount().equals(rule.getUsedTimes())) {
                    ruleId = rule.getRuleId();
                }
                flagList.add(flag);
            }
            //判断获取文件的时间是否在授权文件的有效期内
            if (!flagList.contains(true)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_TIME_IS_ERROR.getErrorCode());
            }
            //判断授权文件规则密码次数
            if (ruleId == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_TIMES_IS_NULL.getErrorCode());
            }

            //4.判断授权文件的剩余次数是否小于设置的次数
            OperateDeviceAuthFileDTO deviceAuthFileDTO = new OperateDeviceAuthFileDTO();
            DeviceAuthFileVO effectiveAuthFile = iOperateDeviceWhiteListAuthFileServiceClient.getEffectiveAuthFile(deviceAuthFileDTO);
            if (effectiveAuthFile == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_FILE_IS_NULL.getErrorCode());
            }

            Map<String, String> data = new HashMap<>();
            data.put("authFileUrl", effectiveAuthFile.getAuthFileUrl());
            data.put("authId", effectiveAuthFile.getAuthId());
            data.put("ruleId", ruleId);
            data.put("consumeFileName", effectiveAuthFile.getFileName());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);

        } catch (Exception e) {
            throw new DataAccessException("【Equip_getWhiteListAuthFile】一体式人脸识别门禁用户获取授权文件失败", e);
        }
    }


    /**
     * <desc>
     * 云门禁（一体式人脸识别门禁）上传设备的激活状态
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-08-12 15:34
     * @Param deviceType 设备类型 1人脸识别云对讲门禁 2人脸识别仪  3一体式人脸识别门禁
     * @Param time 激活时间
     * @Param mac 设备的Mac地址
     * @Param activationmMsg 激活的文件新
     * @Param ruleId  授权文件的规则id
     * @Param authId  授权文件的规则id
     * @Return
     * @Exception
     */
    @UnParamEncrypt
    @PostMapping("/device/entrance/uploadActivateStatus")
    @ResponseBody
    public Object uploadActivateStatus(String deviceType, String time, String mac, String ruleId, String authId, String consumeFileName, HttpServletRequest request) {
        try {

            Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
            deviceType = params.get("deviceType").toString();
            mac = params.get("mac").toString();
            //activationmMsg = params.get("activationmMsg").toString();
            ruleId = params.get("ruleId").toString();
            authId = params.get("authId").toString();
            time = params.get("time").toString();
            consumeFileName = params.get("consumeFileName").toString();

            if (StringUtils.isBlank(deviceType)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PASSWORD_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(mac)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_NULL.getErrorCode());
            }
            //1判断设备mac地址是否在白名单中
            OperateDeviceWhiteListVO whiteListByMac = deviceWhiteListServiceClient.getWhiteListByMac(mac);
            if (whiteListByMac == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DEVICE_MAC_IS_NULL.getErrorCode());
            }
            //保存授权文件消息信息表
            OperateDeviceWhiteListAuthFileConsumeRecordsDTO consumeRecordsDTO = new OperateDeviceWhiteListAuthFileConsumeRecordsDTO();
            consumeRecordsDTO.setConsumeNum(1);
            consumeRecordsDTO.setDeviceActivateTime(time);
            consumeRecordsDTO.setDeviceMac(mac);
            consumeRecordsDTO.setConsumeFileName(consumeFileName);
            consumeRecordsDTO.setDeviceType(Integer.parseInt(deviceType));
            consumeRecordsDTO.setAuthId(authId);
            consumeRecordsDTO.setRuleId(ruleId);
            authFileConsumeRecordsServiceClient.save(consumeRecordsDTO);


            //更新白名单设备信息
            OperateDeviceWhiteListDTO operateDeviceWhiteListDTO = new OperateDeviceWhiteListDTO();
            operateDeviceWhiteListDTO.setAuthId(authId);
            operateDeviceWhiteListDTO.setDeviceType(Integer.parseInt(deviceType));
            operateDeviceWhiteListDTO.setMacAddress(mac);
            operateDeviceWhiteListDTO.setActivateTime(time);
            operateDeviceWhiteListDTO.setAuthFileName(consumeFileName);
            deviceWhiteListServiceClient.updateStatusByAuthIdAndMAC(operateDeviceWhiteListDTO);
            //更新授权文件信息
            OperateDeviceAuthFileDTO operateDeviceAuthFileDTO = new OperateDeviceAuthFileDTO();
            operateDeviceAuthFileDTO.setAuthId(authId);
            operateDeviceAuthFileDTO.setUsedTimes("1");
            operateDeviceAuthFileDTO.setEffectiveTimes("1");
            iOperateDeviceWhiteListAuthFileServiceClient.updateAuthFileByAuthId(operateDeviceAuthFileDTO);
            //更新授权文件规则信息
            OperateDeviceWhiteListAuthRulesDTO authRulesDTO = new OperateDeviceWhiteListAuthRulesDTO();
            authRulesDTO.setRuleId(ruleId);
            authRulesDTO.setUsedTimes(1);
            iOperateDeviceWhiteListAuthRulesServiceClient.updateWhiteListAuthRulesByRuleId(authRulesDTO);


            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());

        } catch (Exception e) {
            throw new DataAccessException("【Equip_uploadActivateStatus】一体式人脸识别门禁用户获取授权文件失败", e);
        }
    }
}
